<!DOCTYPE html>
<html>

	<head>
		<meta charset="UTF-8">
		<title>Snap Draggable - jQuery EasyUI Demo</title>
		<link rel="stylesheet" type="text/css" href="../../../../js/lib/jquery-easyui-v1.5.1/themes/default/easyui.css">
		<link rel="stylesheet" type="text/css" href="../../../../js/lib/jquery-easyui-v1.5.1/themes/icon.css">
		<link rel="stylesheet" type="text/css" href="../../demo.css">
		<script type="text/javascript" src="../../../../js/lib/jquery-easyui-v1.5.1/jquery.min.js"></script>
		<script type="text/javascript" src="../../../../js/lib/jquery-easyui-v1.5.1/jquery.easyui.min.js"></script>
		<style type="text/css">
			.background {
				position: absolute;
				z-index: 0;
				width: 100%;
			}
			
			.row {
				height: 40px;
				width: 100%;
			}
			
			.cell {
				width: 40px;
				height: 40px;
				display: inline-block;
			}
			
			.even {
				background-color: lightgreen;
			}
			
			.odd {
				background-color: lightcoral;
			}
		</style>
	</head>

	<body>
		<h2>Snap Draggable</h2>
		<p>This sample shows how to snap a draggable object to a 40x40 grid.</p>
		<div style="margin:20px 0;"></div>
		<div class="easyui-panel" style="position:relative;overflow:hidden;width:500px;height:300px">
			<div class="background"></div>
			<div class="easyui-draggable" data-options="onDrag:onDrag" style="width:120px;height:120px;background:#fafafa;border:1px solid #ccc;position: absolute;z-index: 1;">
				以40px为单位进行移动
			</div>
		</div>
		<script>
			function createBackgroundGrid() {
				var $container = $(".background");
				var h = 7;
				var flagBg = false;
				while(h > 0) {
					var $row = $('<div class="row"></div>');
					var w = 12;
					while(w > 0) {
						var $cell = $('<div class="cell"></div>');
						if(flagBg) {
							$cell.addClass((w % 2 === 0) ? 'odd' : 'even'); //start with 0
						} else {
							$cell.addClass((w % 2 !== 0) ? 'odd' : 'even'); //start with 0
						}
						$row.append($cell);
						w -= 1;
					}
					$container.append($row);
					h -= 1;
					flagBg = !flagBg;
				}
			}

			function onDrag(e) {
				var d = e.data;
				d.left = repair(d.left);
				d.top = repair(d.top);
				//对坐标进行修正
				function repair(v) {
					var unit = 40;
					//先算出比当前坐标值小的40为单位的最大值
					var r = parseInt(v / unit) * unit;
					//对值进行微修正，在单位小的时候看不出有特别大的差别，所以不用也可以
					//用于在移动的坐标值超出单位的一半的时候，加一个单位的距离
					if(Math.abs(v % unit) > 20) {
						//v为负数的情况只有超出父级容器左上角
						r += v > 0 ? unit : -unit;
					}
					return r;
				}
			}

			createBackgroundGrid();
		</script>

	</body>

</html>